"""
获取问财选股数据:均线粘合，放量，股东户数大于等于1万小于等于5万，
"""
from datetime import datetime
import time

import pandas as pd
from DrissionPage import ChromiumPage
from DrissionPage import WebPage
from DrissionPage._units.listener import DataPacket
from DrissionPage.errors import ElementNotFoundError

from x01_stock.xx_util.DBUtil import SqlHelper

page = ChromiumPage()
page.listen.start('https://www.iwencai.com/customized/chart/get-robot-data')

page.get(
    'https://www.iwencai.com/unifiedwap/result?w=%E5%9D%87%E7%BA%BF%E7%B2%98%E5%90%88%EF%BC%8C%E6%94%BE%E9%87%8F%EF%BC%8C%E8%82%A1%E4%B8%9C%E6%88%B7%E6%95%B0%E5%A4%A7%E4%BA%8E%E7%AD%89%E4%BA%8E1%E4%B8%87%E5%B0%8F%E4%BA%8E%E7%AD%89%E4%BA%8E5%E4%B8%87%EF%BC%8C&querytype=stock&addSign=1723073356153')
time.sleep(3)
try:  # header = res.request.postData
    stat_date = datetime.now().date().strftime('%Y-%m-%d')
    res = page.listen.wait()  # 等待并获取一个数据包
    # print(res.response.body)
    data1 = res.response.body['data']['answer'][0]['txt'][0]['content']['components'][0]['data']['datas']
    #
    # 第一个查询：相关   插入问财返回的基本信息
    for data in data1:
        data = dict(sorted(data.items(), key=lambda item: item[0]))
        print(data)
        sql = (
            f"INSERT INTO `z_sproot_series`.`stock_wencai_junxiannianhe` (trade_date,chengbenshangxian90pct,chengbenxiaxiang90pct,"
            f"mairuxinhao,jujia_hbzz,pingjunchengben,jishuxingtai,shoupanhuoli,stock_price,chg_pct,gudong_hbzzl,stock_code ,stock_name,fangliang,"
            f"jizhongdu70pct,jizhongdu90pct,jzd90_paiming) values ('{stat_date}',")
        for key, value in data.items():
            print(key + ':' + str(value))
            if key != 'market_code' and key != 'code':
                print(type(value))
                if type(value) == str:
                    sql = sql + '"' + str(value) + '",'
                else:
                    sql = sql + str(value) + ','
        sql = sql[:-1] + ');'
        print('--------------------------------')
        print(sql)
        SqlHelper.get_instance().execute_curd(sql)
    print('点击获取表现的数据')

    # # 【第二个查询】
    # page.ele('@text()=表现').click()
    # time.sleep(3)
    # res2 = page.listen.wait()
    # data2 = res2.response.body['data']['answer'][0]['txt'][0]['content']['components'][0]['data']['datas']
    #
    # # print(data2)
    # for data in data2:
    #     data = dict(sorted(data.items(), key=lambda item: item[0]))
    #     print(data)
    #     stock_code = ''
    #     sql = ('update stock_wencai_choumajizhong set nianchuzhijinzhangfu = %s ,jin10rizhangfu = %s,jin20rizhangfu = %s , jin3rizhangfu = %s,'
    #                                      'jin5rizhangfu = %s  ,jin1yuerizhangfu = %s,jin1nianzhangfu = %s,jin3yuezhangfu = %s    ')
    #     set_value = []
    #     for key in data.keys():
    #         if key == 'code' or key == 'market_code' or key == '最新价' or key == '最新涨跌幅' or key == '股票简称':
    #             continue
    #         elif key == '股票代码':
    #             stock_code = data.get(key)
    #         else:
    #             if type(data[key]) == float or type(data[key]) == int:
    #                 set_value.append(key + ':' + str(round(data.get(key), 2)))
    #             else:
    #                 set_value.append(key + ':' + data.get(key))
    #     print(set_value)
    #     sql = sql + ' where stock_code = "' + stock_code + '" and trade_date = "' + stat_date + '";'
    #     print(sql)
    #     SqlHelper.get_instance().execute_curd(sql, set_value)
    # #
    # # 【 第三个查询 技术】
    # page.ele('@text()=技术').click()
    # time.sleep(3)
    # res3 = page.listen.wait()
    # data3 = res3.response.body['data']['answer'][0]['txt'][0]['content']['components'][0]['data']['datas']
    #
    # for data in data3:
    #     data = dict(sorted(data.items(), key=lambda item: item[0]))
    #     print(data)
    #     stock_code = ''
    #     sql = ('update stock_wencai_choumajizhong set ddesanhu = %s ,geguredu = %s , zhulizijin = %s ,suoshugainian = %s, huanshoulv = %s ,'
    #            'jingjialiang = %s ,jingjiajin_e = %s ')
    #     set_value = []
    #     for key in data.keys():
    #         if key == 'code' or key == 'market_code' or key == '最新价' or key == '最新涨跌幅' or key == '股票简称' or key.startswith('技术形态') or key.startswith('集中度90'):
    #             continue
    #         elif key == '股票代码':
    #             stock_code = data.get(key)
    #         else:
    #             set_value.append(data.get(key))
    #     # print(set_value) 如果表格中有 -- 则返回的数据直接少了这个字段，导致更新数据失败。暂不处理
    #     sql = sql + ' where stock_code = "' + stock_code + '" and trade_date = "' + stat_date + '";'
    #     print(sql)
    #     SqlHelper.get_instance().execute_curd(sql, set_value)
    #
    # # 第四个查询
    # page.ele('@text()=估值').click()
    # time.sleep(3)
    # res4 = page.listen.wait()
    # data4 = res4.response.body['data']['answer'][0]['txt'][0]['content']['components'][0]['data']['datas']
    #
    # for data in data4:
    #     data = dict(sorted(data.items(), key=lambda item: item[0]))
    #     print(data)
    #     stock_code = ''
    #     sql = ('update stock_wencai_choumajizhong set aguliutongshizhi = %s ,qiyejiazhi = %s , peg = %s ,shijinglv_pb = %s, shiyinlv_pe = %s '
    #                         ',shixiaolv_ps = %s,shiyinlv_ttm = %s ,zongshizhi = %s,chengjiaoliang = %s ')
    #     set_value = []
    #     for key in data.keys():
    #         if key == 'code' or key == 'market_code' or key == '最新价' or key == '最新涨跌幅' or key == '股票简称' or key.startswith('换手率'):
    #             continue
    #         elif key == '股票代码':
    #             stock_code = data.get(key)
    #         else:
    #             set_value.append(data.get(key))
    #     # print(set_value) #如果表格中有 -- 则返回的数据直接少了这个字段，导致更新数据失败。暂不处理
    #     sql = sql + ' where stock_code = "' + stock_code + '" and trade_date = "' + stat_date + '";'
    #     # print(sql)
    #     SqlHelper.get_instance().execute_curd(sql, set_value)
    #
    # # 第五个查询
    #
    # page.ele('@text()=资产负债').click()
    # time.sleep(3)
    # res5 = page.listen.wait()
    # data5 = res5.response.body['data']['answer'][0]['txt'][0]['content']['components'][0]['data']['datas']
    #
    # for data in data5:
    #     data = dict(sorted(data.items(), key=lambda item: item[0]))
    #     print(data)
    #     stock_code = ''
    #     sql = (
    #         'update stock_wencai_choumajizhong set fuzhaiheji = %s ,zongzichan = %s , zichanfuzhailv = %s ')
    #     set_value = []
    #     for key in data.keys():
    #         if key == '股票代码':
    #             stock_code = data.get(key)
    #         elif key.startswith('负债合计') or key.startswith('资产总计') or key.startswith('资产负债率'):
    #             set_value.append(data.get(key))
    #         else:
    #             continue
    #     # print(set_value)  # 如果表格中有 -- 则返回的数据直接少了这个字段，导致更新数据失败。暂不处理
    #     sql = sql + ' where stock_code = "' + stock_code + '" and trade_date = "' + stat_date + '";'
    #     # print(sql)
    #     SqlHelper.get_instance().execute_curd(sql, set_value)
    #
    # # 第六个查询 -- 利润
    # page.ele('@text()=利润').click()
    # time.sleep(3)
    # res4 = page.listen.wait()
    # data4 = res4.response.body['data']['answer'][0]['txt'][0]['content']['components'][0]['data']['datas']
    #
    # for data in data4:
    #     data = dict(sorted(data.items(), key=lambda item: item[0]))
    #     print(data)
    #     stock_code = ''
    #     sql = ('update stock_wencai_choumajizhong set zichanjingshouyilv = %s ,jinglirun = %s, guanlifeiyong = %s , yingyechengben = %s ,  '
    #                         'yingyeshouru_tbzzl = %s,yingyeshouru = %s, caiwufeiyong = %s,xiaoshoumaolilv = %s,xiaoshoufeiyong = %s ')
    #     set_value = []
    #     for key in data.keys():
    #         if key == 'code' or key == 'market_code' or key == '最新价' or key == '最新涨跌幅' or key == '股票简称':
    #             continue
    #         elif key == '股票代码':
    #             stock_code = data.get(key)
    #         else:
    #             set_value.append(data.get(key))
    #     # print(set_value)  # 如果表格中有 -- 则返回的数据直接少了这个字段，导致更新数据失败。暂不处理
    #     sql = sql + ' where stock_code = "' + stock_code + '" and trade_date = "' + stat_date + '";'
    #     # print(sql)
    #     SqlHelper.get_instance().execute_curd(sql, set_value)
    #
    # print('查询完成，导出excel')

except ElementNotFoundError:
    print('程序异常退出')
# page.quit()
# 打印响应的JSON数据[0]
